<template>
  <div class="login-container">
    <!-- 顶部标题 -->
    <div class="header">用户登录</div>
    
    <!-- 登录表单 -->
    <div class="form-container">
      <van-form @submit="onSubmit">
        <!-- 手机号输入框 -->
        <van-field
          v-model="loginForm.phone"
          type="tel"
          label=""
          placeholder="手机号码"
          :rules="[{ required: true, message: '请输入手机号码' }]"
        />
        <!-- 密码输入框 -->
        <van-field
          v-model="loginForm.password"
          type="password"
          label=""
          placeholder="密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        />
        
        <!-- 登录按钮 -->
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
        
        <!-- 注册链接 -->
        <div class="register-link">
          <router-link to="/register">去注册</router-link>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import axios from 'axios'
import request from '@/utils/request'

const router = useRouter()
const loginForm = reactive({
  phone: '',
  password: ''
})

const onSubmit = async () => {
  try {
    // 1. 先登录
    const res = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/user/login?userName=${loginForm.phone}&password=${loginForm.password}`)
    if (res.data.code === 200) {
      // 2. 存储 token
      const token = res.data.data
      localStorage.setItem('token', token)
      console.log('Token:', token)
      
      // 3. 获取用户详细信息
      const userRes = await request.get(`/user/getUserByName?userName=${loginForm.phone}`)
      
      if (userRes.data.code === 200) {
        const userInfo = userRes.data.data
        console.log('用户信息:', userInfo)
        console.log('用户ID:', userInfo.userId)
        
        // 4. 存储完整的用户信息
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        router.push('/home')
      } else {
        showToast('获取用户信息失败')
      }
    } else {
      showToast(res.data.message)
    }
  } catch (error) {
    console.error('登录失败:', error)
    showToast('登录失败，请稍后重试')
  }
}
</script>

<style scoped>
.login-container {
  padding: 20px;
  height: 100vh;
  background: #fff;
}

.header {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 40px;
  padding-top: 40px;
}

.form-container {
  margin-top: 20px;
}

.register-link {
  text-align: center;
  margin-top: 16px;
}

.register-link a {
  color: #1989fa;
  text-decoration: none;
}
</style> 